use crate::commands::commands;
use crate::dao;
use crate::models::models::command::Command;
use crate::models::models::commands::basic_command_setting::BasicCommandSetting;
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::{Code, MagicBoxResponse};
use crate::runtime::result::MagicBoxResult;

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_execute_command(command: Command) -> MagicBoxResult<MagicBoxResponse<Command>> {
    let c = commands::new_command(command.name.as_str());
    if c.is_none() {
        return Err(MagicBoxError::new(Code::CommandNotFound, format!("未知命令: {}", command.name.as_str()).as_str()));
    }

    let command_basic_setting = dao::setting::get_setting::<BasicCommandSetting>(format!("command.{}.config", command.name.as_str()).as_str());
    if command_basic_setting.is_none() || command_basic_setting.unwrap().append_to_history == true {
        let result = dao::command::insert_command_history(&command);
        if result.is_err() {
            log::error!("保存命令历史失败: {}", result.unwrap_err().to_string());

            return Err(MagicBoxError::new(Code::UndefinedError, "保存命令历史失败"));
        }
    }

    Ok(MagicBoxResponse::new_success(c.unwrap().execute(command).await))
}
